package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.annotation.CacheFind;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.EasyUITree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Cx
 * @stage JT Of Fourth stage
 * @creat 2020-11-27 15:17
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired(required = false)
    private ItemCatMapper itemCatMapper;
    @Autowired(required = false)
    private Jedis jedis;

    @Override
    @CacheFind(key = "ITEM_CAT")
    public ItemCat findItemCatById(Long itemCatId) {
        return itemCatMapper.selectById(itemCatId);
    }

    /**
     * 1.根据parentId 查询子级目录信息
     * 2.获取ItemCatList集合,之后将List集合转化为VOList集合
     * 3.返回数据
     *
     * @param parentId
     */
    @Override
    @CacheFind(key = "ITEM_CAT_PARENT", seconds = 7 * 24 * 60 * 60)
    public List<EasyUITree> findItemCatList(long parentId) {
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<ItemCat> catList = itemCatMapper.selectList(queryWrapper);
        List<EasyUITree> treeList = new ArrayList<>(catList.size()); /* list集合转换 */
        for (ItemCat itemCat : catList) {
            long id = itemCat.getId();
            String text = itemCat.getName();
            String state = itemCat.getIsParent() ? "closed" : "open"; /* 如果是父级 默认应该closed */
            EasyUITree easyUITree = new EasyUITree(id, text, state);
            treeList.add(easyUITree);
        }
        return treeList;
    }

    // 实现缓存
    @Override
    public List<EasyUITree> findItemCatCache(long parentId) {
        List<EasyUITree> treeList = new ArrayList<>();
        // 定义key
        String key = "ITEM_CAT_PARENT::" + parentId;
        // 从缓存获取对象
        if (jedis.exists(key)) {
            long start = System.currentTimeMillis();
            String json = jedis.get(key);
            treeList = ObjectMapperUtil.toObject(json, treeList.getClass());
            long end = System.currentTimeMillis();
            System.out.println("查询了REDIS缓存-->" + "用时: " + (end - start));
        } else {
            long start = System.currentTimeMillis();
            treeList = findItemCatList(parentId);
            String json = ObjectMapperUtil.toJson(treeList);
            jedis.setex(key, 7 * 24 * 60 * 60, json);
            long end = System.currentTimeMillis();
            System.out.println("查询了数据库-->" + "用时: " + (end - start));
        }
        return treeList;
    }

}
